#!/bin/bash
set -e
LANG=en_US.utf8
LOG_INFO()
{
    local content=${1}
    echo -e "\033[32m[INFO][CITA] ${content}\033[0m"
}

LOG_ERROR()
{
    local content=${1}
    echo -e "\033[31m[ERROR][CITA] ${content}\033[0m"
}

Download()
{
    local url=${1}
    local file=$(basename ${url})
    if [ ! -e ${file} ]; then
        curl -LO ${url}
    fi
}

# Download
LOG_INFO "Download solc ..."
Download https://github.com/ethereum/solidity/releases/download/v0.4.24/solc-static-linux

LOG_INFO "Download cita-cli ..."
Download https://github.com/citahub/cita-cli/releases/download/20.2.2/cita-cli-x86_64-musl-tls-20.2.2.tar.gz

LOG_INFO "Download jq ..."
Download https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64

LOG_INFO "Download cita_sm2_sm3 ..."
Download https://github.com/citahub/cita/releases/download/v20.2.0/cita_sm2_sm3.tar.gz

# Install
LOG_INFO "Install ..."
cp solc-static-linux solc
chmod +x solc
cp jq-linux64 jq
chmod +x jq
tar -zxf cita-cli-x86_64-musl-tls-20.2.2.tar.gz
chmod +x cita-cli
tar -zxf cita_sm2_sm3.tar.gz


# Startup
LOG_INFO "Startup cita chain"
cd cita_sm2_sm3

bin/cita create --super_admin "0xae959a512837e35a7a777e75ddd0d87e46534711" --nodes "127.0.0.1:4000,127.0.0.1:4001,127.0.0.1:4002,127.0.0.1:4003" || true
sleep 10
bin/cita setup test-chain/0
bin/cita setup test-chain/1
bin/cita setup test-chain/2
bin/cita setup test-chain/3

bin/cita start test-chain/0
bin/cita start test-chain/1
bin/cita start test-chain/2
bin/cita start test-chain/3
sleep 30
cd ..

# Startup
LOG_INFO "Compile contract ..."
./solc --overwrite --bin --abi SimpleStorage.sol -o output

# Deploy
LOG_INFO "Deploy contract ..."
sendtx_output=$(./cita-cli rpc sendRawTransaction \
    --code 0x`cat output/SimpleStorage.bin` \
    --private-key 0x14d692beef6d14273980a3d628845362b10436be8a293ab55ffa5d7a49218807 --algorithm sm2)
echo "sendtx output: $sendtx_output"
tx_hash=$(echo $sendtx_output | ./jq -r .result.hash)
echo "tx_hash : $tx_hash"
sleep 10
receipt=$(./cita-cli rpc getTransactionReceipt --hash $tx_hash)
echo "receipt : $receipt"
contractAddress=$(echo $receipt | ./jq -r .result.contractAddress)
echo "contractAddress : $contractAddress"
./cita-cli store abi --address $contractAddress --content `cat output/SimpleStorage.abi` --private-key 0x14d692beef6d14273980a3d628845362b10436be8a293ab55ffa5d7a49218807 --algorithm sm2
sleep 10

# Done
LOG_INFO "Done!!!"
